package shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * Shiro 入门程序
 * 1.鉴权
 * 2.授权
 * 3.通过实现类，回调类方法进行鉴权和授权
 */
public class ShiroTest {

    /**
     * 登录鉴权
     */
    @Test
    public void testShiro1(){
        //1.加载ini配置文件创建SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-auth-1.ini");
        //2.获取securityManager
        SecurityManager securityManager = factory.getInstance();
        //3.将securityManager绑定到当前运行环境
        SecurityUtils.setSecurityManager(securityManager);
        //4.创建主体(此时的主体还为经过认证)
        Subject subject = SecurityUtils.getSubject();
        /**
         * 模拟登录，和传统等不同的是需要使用主体进行登录
         */
        //5.构造主体登录的凭证（即用户名/密码）
        //第一个参数：登录用户名，第二个参数：登录密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("zhangsan", "123456");
        //6.主体登录
        subject.login(usernamePasswordToken);
        //7.验证是否登录成功
        System.out.println(subject.isAuthenticated());
        //8.登录成功获取数据
        //getPrincipal 获取登录成功的安全数据
        System.out.println(subject.getPrincipal());
    }

    /**
     * 授权
     */
    @Test
    public void testShiro2(){
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-auth-2.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken passwordToken = new UsernamePasswordToken("zhangsan", "123456");
        subject.login(passwordToken);

        boolean hasRole = subject.hasRole("role1");
        System.out.println("hasRole="+hasRole);
        boolean permitted = subject.isPermitted("user.delete");
        System.out.println("permitted="+permitted);
    }

    /**
     * 通过实现一个鉴权和授权类，来实现，鉴权和授权操作
     */
    @Test
    public void testShiro3(){
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-auth-3.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken passwordToken = new UsernamePasswordToken("zhangsan", "123456");
        subject.login(passwordToken);

        boolean hasRole = subject.hasRole("role1");
        System.out.println("hasRole="+hasRole);
        boolean permitted = subject.isPermitted("user.deleteAAA");
        System.out.println("permitted="+permitted);
    }
}
